package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.ClueDO;
import com.qk.dto.clue.ClueDTO;
import com.qk.dto.clue.ClueListDTO;
import com.qk.dto.clue.GetCluePoolDTO;
import com.qk.dto.clue.UpdateClueInfoDTO;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.clue.ClueVO;
import com.qk.domain.clue.FalsyClueDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author Just、倾城
 * @created 2025-10-13
 * @description
 *
 */
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public PageResult<FalsyClueDO> getCluePool(GetCluePoolDTO dto) {
        Page<FalsyClueDO> page = new Page<>(dto.getPage(),dto.getPagesize());
        Page<FalsyClueDO> result =this.baseMapper.selectListByConditon(page,dto);
        return PageResult.<FalsyClueDO>builder().rows(result.getRecords()).total(Long.valueOf(result.getTotal()).intValue()).build();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void convertToBussiness(Integer id) {
        //1.修改线索信息
        Clue clue = this.getById(id);
        clue.setStatus(ClueStatusConstants.CONVERT_TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);

        //2.创建商机信息
        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId( null);
        business.setUserId(null);
        business.setNextTime( null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setClueId(clue.getId());
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        this.businessMapper.insert(business);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {
        //1.获取线索信息
        //1.1 将dto转换为对应的实体类
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        //1.2 补全更新时间
        clue.setUpdateTime(LocalDateTime.now());
        //1.3 处理状态 如果当前的线索是第一次被跟进状态2 需要改成3跟进中
        if(Objects.equals(dto.getStatus(), ClueStatusConstants.WAIT_FOLLOW_UP)){
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        }
        //1.4 更新clue表数据
        this.baseMapper.updateById(clue);
        //2.获取线索的跟进记录，信息插入到clue_track_record表
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        //2.1 补全创建时间
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        //2.2 将id置为 null
        clueTrackRecord.setId(null);
        //2.3 设置线索id
        clueTrackRecord.setClueId(clue.getId());
        //2.4 设置线索跟进记录状态默认正常跟进 1正常跟进 2跟进失败 3跟进中
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        //
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        //2.4 插入数据到 clue_track_record表
        this.clueTrackRecordMapper.insert(clueTrackRecord);
    }


    @Override
    public ClueVO getClueInfoById(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        Integer userId = clue.getUserId();
        User user = userMapper.selectById(userId);
        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(
                        ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId, id)
        );
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.ClueTrackRecordVO> list = clueTrackRecords.stream().map(item -> {
            ClueVO.ClueTrackRecordVO vo = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        clueVO.setTrackRecords(list);
        return clueVO;
    }
    private PageResult<ClueDO> clueListMp(ClueListDTO dto){
      Page<ClueDO> page = new Page<>(dto.getPage(),dto.getPagesize());
      Page<ClueDO> result = clueMapper.selectByPageMp(page,dto);
      return PageResult.<ClueDO>builder()
              .total(Long.valueOf(result.getTotal()).intValue())
              .rows(result.getRecords())
              .build();
    }
    @Override
    public PageResult<ClueDO> clueList(ClueListDTO dto) {
        /*PageHelper.startPage(dto.getPage(),dto.getPagesize());
        List<ClueDO> list = this.baseMapper.selectByPage(dto);
        Page<ClueDO> page = (Page<ClueDO>) list;
        PageResult<ClueDO> pageResult = PageResult.<ClueDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(list)
                .build();*/
        return clueListMp(dto);
    }


    @Override
    public void addClue(ClueDTO clueDTO) {
        // 参数校验
        if(ObjectUtil.isEmpty(clueDTO.getPhone())|| ObjectUtil.isEmpty(clueDTO.getChannel())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 将DTO类转换为对应的实体类
        Clue clue = BeanUtil.copyProperties(clueDTO, Clue.class);
        //补全创建时间
        clue.setCreateTime(LocalDateTime.now());
        //补全更新时间
        clue.setUpdateTime(LocalDateTime.now());
        //补全状态
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        this.save(clue);
    }
}
